package com.example.mybatis_plus_use.service.impl;

import com.example.mybatis_plus_use.Exception.CustomException;
import com.example.mybatis_plus_use.entity.User;
import com.example.mybatis_plus_use.enums.Education;
import com.example.mybatis_plus_use.mapper.UserMapper;
import com.example.mybatis_plus_use.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mybatis_plus_use.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import static java.util.Locale.filter;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zjh
 * @since 2025-01-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> GetUserByPartialName(String partialName) {
        return lambdaQuery().like(User::getUsername, partialName).list();
    }

    @Override
    public List<User> GetUserAndOrderDetailByid(Integer id) {
        return userMapper.GetUserAndOrderDetailByid(id);
    }

    @Override
    public Result<String> SaveUser(User user) {
        if (user.getUsername() == null || user.getUsername().isEmpty()) {
            throw new CustomException("用户名不能为空");//设置异常信息
        }//在if中抛出CustomException异常
        try {
            this.save(user); // 直接调用父类的 save 方法
        } catch (DuplicateKeyException e) {
            return Result.error("重复主键异常：" + HttpStatus.CONFLICT);
        }
        return Result.success("保存成功");
    }
    @Override//获取教育程度描述
    public String getEducationDesc(Integer level) {
        return Arrays.stream(Education.values())
                .filter(edu -> edu.getLevel() == level)
                .findFirst()
                .map(Education::getDesc)
                .orElse("无效的教育程度等级");
    }
//Education.values()返回的是枚举类中的所有枚举对象的数组，
// Arrays.stream转为流，filter过滤，findFirst获取第一个元素，map获取描述，orElse获取默认值。
    @Override
    public List<User> getUsersByMinEducation(Integer minLevel) {
        return lambdaQuery()
                .ge(User::getEducation, minLevel)
                .orderByAsc(User::getEducation)
                .list();
    }
   // lambdaQuery是serviceImpl中的方法，lambdaQuery()返回的是一个QueryWrapper对象，
    @Override
    public void updateUserEducation(Long userId, Integer level) {
        Education education = Arrays.stream(Education.values())
                .filter(edu -> edu.getLevel() == level)
                .findFirst()
                .orElseThrow(() -> new CustomException("无效的教育程度等级"));

        User user = getById(userId);
        if (user == null) {
            throw new CustomException("用户不存在");
        }

        user.setEducation(education);
        updateById(user);
    }

    @Override
    public List<User> getUsersByEducation(Education education) {
        return lambdaQuery()
                .eq(User::getEducation, education)
                .list();
    }

    @Override
    public Map<Education, List<User>> getUsersGroupByEducationLevelN(Integer education) {
        List<User> users = getAllUsers();//先把列表转为流然后再分组
        return users.stream()
                .filter(H -> H.getEducation().getLevel() == education)//在最后执行groupingBy方法前使用Filter方法
                .collect(Collectors.groupingBy(User::getEducation));  //筛选条件
    }

    @Override
    public String getNameById(Long authorId) {
        return lambdaQuery()
                .eq(User::getId, authorId)
                .select(User::getUsername)
                .one().getUsername();
    }

    @Override
    public Map<Education, List<User>> getUsersGroupByEducationLevel() {
        List<User> users = getAllUsers();//先把列表转为流然后再分组
        return users.stream()
                .collect(Collectors.groupingBy(User::getEducation));
    }
    private List<User> getAllUsers() {
        return this.list();
    }
}
